﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;

 
	public class HttpHelper
	{
		 

		public static async Task<T> PostAsync<T>(string url,string postData) {
			var json = await PostUrlAsync(url, postData);
			return json.DeserializeObject<T>();

		}

		public static async Task<string> GetUrlAsync(string url )
		{
			string result = "";

			HttpWebRequest req = (HttpWebRequest)WebRequest.Create(url);

			req.Method = "GET";
			req.Headers.Add("X-Bmob-Application-Id", "3b7bc81ed038b60c3cc63922ede49a33");
			req.Headers.Add("X-Bmob-REST-API-Key", "f76a0a13d6ac18cc84cd255a940011cd");
			req.Timeout = 800;//设置请求超时时间，单位为毫秒

			req.ContentType = "application/json";

			  
			 

			HttpWebResponse resp = (HttpWebResponse)req.GetResponse();

			Stream stream = resp.GetResponseStream();

			//获取响应内容
			using (StreamReader reader = new StreamReader(stream, Encoding.UTF8))
			{
				result = await reader.ReadToEndAsync();
			}

			return result;
		}

		/*
   *  url:POST请求地址
   *  postData:json格式的请求报文,例如：{"key1":"value1","key2":"value2"}
   */

		public static async Task<string> PostUrlAsync(string url, string postData)
		{
			string result = "";

			HttpWebRequest req = (HttpWebRequest)WebRequest.Create(url);

			req.Method = "POST";

			req.Timeout = 800;//设置请求超时时间，单位为毫秒

			req.ContentType = "application/json";

			byte[] data = Encoding.UTF8.GetBytes(postData);

			req.ContentLength = data.Length;

			using (Stream reqStream = req.GetRequestStream())
			{
				reqStream.Write(data, 0, data.Length);

				reqStream.Close();
			}

			HttpWebResponse resp = (HttpWebResponse)req.GetResponse();

			Stream stream = resp.GetResponseStream();

			//获取响应内容
			using (StreamReader reader = new StreamReader(stream, Encoding.UTF8))
			{
				result = await reader.ReadToEndAsync();
			}

			return result;
		}
	}
 
